﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Logging;
using VAdvantage.Model;
using VAdvantage.Utility;
using System.Text;
using VAdvantage.DataBase;
using VAdvantage.Classes;
using System.Data;
using VAdvantage.Print;
using VAdvantage.Framework;
using System.IO;

namespace VAdvantage.Apps.AForms
{
    public partial class VPayPrint : UserControl, FormPanel
    {
        # region Private Variables
        String[] bp = null;
        String[] bpba = null;

        private static long serialVersionUID = 1L;
        //Window No	
        private int m_WindowNo = 0;
        //FormFrame	
        private FormFrame m_frame;
        //Used Bank Account	
        private int m_C_BankAccount_ID = -1;

        //Payment Information
        private VAdvantage.Model.MPaySelectionCheck[] m_checks = null;
        //Payment Batch	
        private VAdvantage.Model.MPaymentBatch m_batch = null;
        //Logger		
        private static VLogger log = VLogger.GetVLogger(typeof(VPayPrint));

        VAdvantage.DSProcessWorkflow.ReportInfo rep = null;


        /** BPartner Info Index for Value       */
        private const int BP_VALUE = 0;
        /** BPartner Info Index for Name        */
        private const int BP_NAME = 1;
        /** BPartner Info Index for Contact Name    */
        private const int BP_CONTACT = 2;
        /** BPartner Info Index for Address 1   */
        private const int BP_ADDR1 = 3;
        /** BPartner Info Index for Address 2   */
        private const int BP_ADDR2 = 4;
        /** BPartner Info Index for City        */
        private const int BP_CITY = 5;
        /** BPartner Info Index for Region      */
        private const int BP_REGION = 6;
        /** BPartner Info Index for Postal Code */
        private const int BP_POSTAL = 7;
        /** BPartner Info Index for Country     */
        private const int BP_COUNTRY = 8;
        /** BPartner Info Index for Reference No    */
        private const int BP_REFNO = 9;


        /** BankAccount Info Index for RoutingNo       */
        private const int BPBA_RoutingNo = 0;
        /** BankAccount Info Index for AccountNo       */
        private const int BPBA_AccountNo = 1;
        /** BankAccount Info Index for AccountName     */
        private const int BPBA_AName = 2;
        /** BankAccount Info Index for AccountCity     */
        private const int BPBA_ACity = 3;
        /** BankAccount Info Index for BBAN            */
        private const int BPBA_BBAN = 4;
        /** BankAccount Info Index for IBAN            */
        private const int BPBA_IBAN = 5;
        /** BankAccount Info Index for Bank Name       */
        private const int BA_Name = 6;
        /** BankAccount Info Index for Bank RoutingNo  */
        private const int BA_RoutingNo = 7;
        /** BankAccount Info Index for Bank SwiftCode  */
        private const int BA_SwitftCode = 8;

        #endregion

        public VPayPrint()
        {
            InitializeComponent();
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            Dispose();
        }

        private void btnExport_Click(object sender, RoutedEventArgs e)
        {
            bool res = false;
            String PaymentRule = ((ValueNamePair)cmbPaymentRule.SelectedItem).GetValue();
            log.Info(PaymentRule);

            if (cmbPaySelect.SelectedIndex == -1 || m_C_BankAccount_ID == -1
               || cmbPaymentRule.SelectedIndex == -1 || txtDocumentNo.Text == null)
            {
                ShowMessage.Error("VPayPrintNoRecords", null, "(" + Msg.Translate(Envs.GetCtx(), "C_PaySelectionLine_ID") + "=0)");
                res = false;
            }

            int C_PaySelection_ID = ((KeyNamePair)cmbPaySelect.SelectedItem).GetKey();
            int startDocumentNo = Util.GetValueOfInt(txtDocumentNo.Text);
            log.Config("C_PaySelection_ID=" + C_PaySelection_ID + ", PaymentRule=" + PaymentRule + ", DocumentNo=" + startDocumentNo);

            SaveFileDialog dlg = new SaveFileDialog();
            dlg.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
            dlg.DefaultFileName = Msg.GetMsg(Envs.GetCtx(), "Export");
            if (dlg.ShowDialog() == false)
            {
                return;
            }

            string expFile = dlg.SafeFileName;

            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                m_checks = VAdvantage.Model.MPaySelectionCheck.Get(C_PaySelection_ID, PaymentRule, startDocumentNo, null);

                //
                if (m_checks == null || m_checks.Length == 0)
                {
                    ShowMessage.Error("VPayPrintNoRecords", null, "(" + Msg.Translate(Envs.GetCtx(), "C_PaySelectionLine_ID") + " #0");
                    res = false;
                    //return false;
                }
                else
                {
                    res = true;
                }
                m_batch = VAdvantage.Model.MPaymentBatch.GetForPaySelection(Envs.GetCtx(), C_PaySelection_ID, null);
                //return true;
                if (!res)
                {
                    return;
                }
                //  Get File Info
                Dictionary<VAdvantage.Model.MPaySelectionCheck, String> oldCheckValues = new Dictionary<VAdvantage.Model.MPaySelectionCheck, string>();

                //  Create File
                foreach (VAdvantage.Model.MPaySelectionCheck check in m_checks)
                {
                    //oldCheckValues.put(check,(String)check.get_ValueOld("DocumentNo"));
                    oldCheckValues.Add(check, Util.GetValueOfString(check.Get_ValueOld("DocumentNo")));
                }

                List<String[]> busPart = new List<String[]>();
                List<String[]> bankAcc = new List<String[]>();
                List<String> comm = new List<String>();
                List<String> DocumentNo = new List<String>();
                List<String> PayDate = new List<String>();
                List<String> ISOCode = new List<String>();
                List<String> PayAmt = new List<String>();

                ////  write lines
                for (int i = 0; i < m_checks.Length; i++)
                {
                    VAdvantage.Model.MPaySelectionCheck mpp = m_checks[i];
                    if (mpp == null)
                        continue;
                    //  BPartner Info
                    bp = GetBPartnerInfo(mpp.GetC_BPartner_ID());
                    busPart.Add(bp);
                    //  TarGet BankAccount Info
                    bpba = GetBPBankAccountInfo(mpp.GetC_BP_BankAccount_ID());
                    bankAcc.Add(bpba);
                    //  Comment - list of invoice document no
                    StringBuilder comment = new StringBuilder();
                    VAdvantage.Model.MPaySelectionLine[] psls = mpp.GetPaySelectionLines(false);
                    for (int l = 0; l < psls.Length; l++)
                    {
                        if (l > 0)
                            comment.Append(", ");
                        comment.Append(psls[l].GetInvoice().GetDocumentNo());
                    }
                    comm.Add(comment.ToString());
                    DocumentNo.Add(mpp.GetDocumentNo());
                    PayDate.Add(mpp.GetParent().GetPayDate().ToString());
                    ISOCode.Add(VAdvantage.Model.MCurrency.GetISO_Code(Envs.GetContext(), mpp.GetParent().GetC_Currency_ID()));
                    PayAmt.Add(mpp.GetPayAmt().ToString());
                }

                //int no = MPaySelectionCheck.exportToFile(m_checks, fc.getSelectedFile());

                //ShowMessage.Info("Saved",null, dlg.getSelectedFile().getAbsolutePath() + "\n"
                //    + Msg.GetMsg(Envs.GetCtx(), "NoOfLines") + "=" + no);

                Dispatcher.BeginInvoke(delegate
                {
                    SetBusy(true);
                    Export(m_checks, expFile, dlg, comm, busPart, bankAcc, DocumentNo, PayDate, ISOCode, PayAmt);
                    SetBusy(false);
                    ShowMessage.AskMessage("VPayPrintSuccess?", true, "", "").Closed += (sc, ec) =>
                    {
                        SetBusy(true);
                        bool ask = false;
                        if (false.Equals(((Message)sc).DialogResult))
                        {
                            ask = false;
                        }
                        else
                        {
                            ask = true;
                        }
                        System.Threading.ThreadPool.QueueUserWorkItem(delegate
                        {
                            if (ask)
                            {
                                // int lastDocumentNo = 
                                VAdvantage.Model.MPaySelectionCheck.ConfirmPrint(m_checks, m_batch);
                                // document No not updated
                            }
                            else
                            {
                                foreach (VAdvantage.Model.MPaySelectionCheck check in m_checks)
                                {
                                    check.SetCheckNo(oldCheckValues[check]);
                                    check.Save();
                                }
                            }
                            Dispatcher.BeginInvoke(delegate
                            {
                                SetBusy(false);
                                Dispose();
                            });
                        });
                    };
                });
            });

            //  Cmd_Export();
        }

        private void Export(VAdvantage.Model.MPaySelectionCheck[] m_checks, string expFile, SaveFileDialog save, List<String> comment, List<String[]> Partners, List<String[]> account, List<String> docNo, List<String> payDate, List<String> ISOCode, List<String> payAmt)
        {
            StreamWriter sw = null;
            int noLines = 0;
            using (sw = new StreamWriter(save.OpenFile()))
            {
                // sw.Write("abc");
                char x = '"';      //  ease
                StringBuilder line = null;
                //  write header
                line = new StringBuilder();
                line.Append(x).Append("Value").Append(x).Append(",")
                    .Append(x).Append("Name").Append(x).Append(",")
                    .Append(x).Append("Contact").Append(x).Append(",")
                    .Append(x).Append("Addr1").Append(x).Append(",")
                    .Append(x).Append("Addr2").Append(x).Append(",")
                    .Append(x).Append("City").Append(x).Append(",")
                    .Append(x).Append("State").Append(x).Append(",")
                    .Append(x).Append("ZIP").Append(x).Append(",")
                    .Append(x).Append("Country").Append(x).Append(",")
                    .Append(x).Append("ReferenceNo").Append(x).Append(",")
                    .Append(x).Append("BPRoutingNo").Append(x).Append(",")
                    .Append(x).Append("BPAccountNo").Append(x).Append(",")
                    .Append(x).Append("BPAName").Append(x).Append(",")
                    .Append(x).Append("BPACity").Append(x).Append(",")
                    .Append(x).Append("BPBBAN").Append(x).Append(",")
                    .Append(x).Append("BPIBAN").Append(x).Append(",")
                    .Append(x).Append("BAName").Append(x).Append(",")
                    .Append(x).Append("BARoutingNo").Append(x).Append(",")
                    .Append(x).Append("BASwiftCode").Append(x).Append(",")
                    .Append(x).Append("DocumentNo").Append(x).Append(",")
                    .Append(x).Append("PayDate").Append(x).Append(",")
                    .Append(x).Append("Currency").Append(x).Append(",")
                    .Append(x).Append("PayAmount").Append(x).Append(",")
                    .Append(x).Append("Comment").Append(x)
                    .Append(Envs.NL);
                sw.Write(line.ToString());
                noLines++;

                for (int i = 0; i < Partners.Count; i++)
                {
                    line = new StringBuilder();
                    line.Append(x).Append(bp[BP_VALUE]).Append(x).Append(",")   // Value
                        .Append(x).Append(Partners[i][BP_NAME]).Append(x).Append(",")    // Name
                        .Append(x).Append(Partners[i][BP_CONTACT]).Append(x).Append(",") // Contact
                        .Append(x).Append(Partners[i][BP_ADDR1]).Append(x).Append(",")   // Addr1
                        .Append(x).Append(Partners[i][BP_ADDR2]).Append(x).Append(",")   // Addr2
                        .Append(x).Append(Partners[i][BP_CITY]).Append(x).Append(",")    // City
                        .Append(x).Append(Partners[i][BP_REGION]).Append(x).Append(",")  // State
                        .Append(x).Append(Partners[i][BP_POSTAL]).Append(x).Append(",")  // ZIP
                        .Append(x).Append(Partners[i][BP_COUNTRY]).Append(x).Append(",") // Country
                        .Append(x).Append(Partners[i][BP_REFNO]).Append(x).Append(",")   // ReferenceNo
                        .Append(x).Append(account[i][BPBA_RoutingNo]).Append(x).Append(",")   // Routing No (as of BPBankAccount
                        .Append(x).Append(account[i][BPBA_AccountNo]).Append(x).Append(",")   // AccountNo
                        .Append(x).Append(account[i][BPBA_AName]).Append(x).Append(",")       // Account Name
                        .Append(x).Append(account[i][BPBA_ACity]).Append(x).Append(",")       // Account City
                        .Append(x).Append(account[i][BPBA_BBAN]).Append(x).Append(",")        // BBAN
                        .Append(x).Append(account[i][BPBA_IBAN]).Append(x).Append(",")        // IBAN
                        .Append(x).Append(account[i][BA_Name]).Append(x).Append(",")          // Bank Name
                        .Append(x).Append(account[i][BA_RoutingNo]).Append(x).Append(",")     // Bank RoutingNo
                        .Append(x).Append(account[i][BA_SwitftCode]).Append(x).Append(",")    // SwiftCode
                        //  Payment Info
                        .Append(x).Append(docNo[i]).Append(x).Append(",")    // DocumentNo
                        .Append(payDate[i]).Append(",")               // PayDate
                        .Append(x).Append(ISOCode[i]).Append(x).Append(",")    // Currency
                        .Append(payAmt[i]).Append(",")                // PayAmount
                        .Append(x).Append(comment[i]).Append(x)     // Comment
                        .Append(Envs.NL);
                    sw.Write(line.ToString());
                    noLines++;
                }
                //  write line
                sw.Flush();
                sw.Close();
            }
        }

        private void btnPrint_Click(object sender, RoutedEventArgs e)
        {
            SetBusy(true);
            Cmd_Print();
        }

        private void btnEFT_Click(object sender, RoutedEventArgs e)
        {
            Cmd_EFT();
        }

        private void chkShowPrinted_Click(object sender, RoutedEventArgs e)
        {
            LoadPaySelections();
        }

        private void cmbPaymentRule_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            LoadPaymentRuleInfo();
        }

        private void cmbPaySelect_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            LoadPaySelectInfo();
        }

        /// <summary>
        /// Maun fUNCTION
        /// </summary>
        /// <param name="windowNo"></param>
        /// <param name="frame"></param>
        public void Init(int windowNo, FormFrame frame)
        {
            log.Info("");
            m_WindowNo = windowNo;
            m_frame = frame;
            try
            {
                this.Visibility = System.Windows.Visibility.Visible;
                m_frame.ContentGrid.Children.Add(this);
                m_frame.SetTitle("Payment Print/Export");
                JbInit();
                DynInit();
                SetBusy(false);
            }
            catch (Exception e)
            {
                log.Log(Level.SEVERE, "", e);
            }
            //m_frame.Width = 500;
            m_frame.MaxHeight = 215;
        }

        private void JbInit()
        {
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                string eft = Msg.GetMsg(Envs.GetCtx(), "EFT");
                string printpay = Msg.GetMsg(Envs.GetCtx(), "ShowPrintedPayments");
                string pay = Msg.Translate(Envs.GetCtx(), "C_PaySelection_ID");
                string bank = Msg.Translate(Envs.GetCtx(), "C_BankAccount_ID");
                string rule = Msg.Translate(Envs.GetCtx(), "PaymentRule");
                string chk = Msg.GetMsg(Envs.GetCtx(), "Check No");
                string payments = Msg.GetMsg(Envs.GetCtx(), "NoOfPayments");
                string balance = Msg.Translate(Envs.GetCtx(), "CurrentBalance");
                string curency = Msg.Translate(Envs.GetCtx(), "C_Currency_ID");
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => TextBinding(eft, printpay, pay, bank, rule, chk, payments, balance, curency));
            });
        }

        private void TextBinding(string eft, string printpay, string pay, string bank, string rule, string chk, string payments, string balance, string curency)
        {
            // btnEFT.Content = eft;
            chkShowPrinted.Content = printpay;
            lblPaySelect.Content = pay;
            lblBank.Content = bank;
            lblPaymentRule.Content = rule;
            lblDocumentNo.Content = chk;
            lblNoPayments.Content = payments;
            lblBalance.Content = balance;
            lblCurrency.Content = curency;
            lblNoPaymentsCount.Content = "0";
            txtBalance.IsReadOnly = true;
        }

        /// <summary>
        /// Dynamic Load
        /// </summary>
        private void DynInit()
        {
            log.Config("");
            LoadPaySelections();
        }

        /// <summary>
        /// 	Dispose
        /// </summary>
        public void Dispose()
        {
            if (m_frame != null)
            {
                m_frame.Dispose();
            }
            m_frame = null;

        }

        /// <summary>
        /// Load Pay Selections
        /// </summary>
        private void LoadPaySelections()
        {
            cmbPaySelect.Items.Clear();
            int AD_Client_ID = Envs.GetCtx().GetAD_Client_ID();
            bool printCheck = (bool)chkShowPrinted.IsChecked;
            IDataReader idr = null;
            try
            {
                System.Threading.ThreadPool.QueueUserWorkItem(delegate
                {
                    //  Load PaySelect
                    StringBuilder sql = new StringBuilder("SELECT C_PaySelection_ID, Name || ' - ' || " + DB.TO_CHAR("TotalAmt",
                        DisplayType.Number, Envs.GetAD_Language(Envs.GetCtx())) + " FROM C_PaySelection "
                        + "WHERE AD_Client_ID=" + AD_Client_ID + " AND Processed='Y' AND IsActive='Y'");
                    if (!printCheck)
                    {
                        sql.Append(" AND EXISTS (SELECT * FROM C_PaySelectionCheck psc" +
                                   " WHERE psc.C_PaySelection_ID = C_PaySelection.C_PaySelection_ID	AND psc.IsPrinted = 'N') ");
                    }
                    sql.Append("ORDER BY PayDate DESC, C_PaySelection_ID DESC");

                    idr = DB.ExecuteReader(sql.ToString(), null, null);
                    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(delegate
                    {
                        while (idr.Read())
                        {
                            KeyNamePair pp = new KeyNamePair(Util.GetValueOfInt(idr[0]), Util.GetValueOfString(idr[1]));
                            cmbPaySelect.Items.Add(pp);

                        }
                        idr.Close();
                        if (cmbPaySelect.Items.Count == 0)
                        {
                            ShowMessage.Info("VPayPrintNoRecords", null, "", "");
                        }
                        else
                        {
                            cmbPaySelect.SelectedIndex = 0;
                        }

                    });
                });

            }
            catch (Exception ev)
            {
                if (idr != null)
                {
                    idr.Close();
                    idr = null;
                }
                //log.Log(Level.SEVERE, sql.ToString(), ev);
            }
        }

        /// <summary>
        /// Set Payment Selection
        /// </summary>
        /// <param name="C_PaySelection_ID">id</param>
        public void SetPaySelection(int C_PaySelection_ID)
        {
            if (C_PaySelection_ID == 0)
            {
                return;
            }
            //
            for (int i = 0; i < cmbPaySelect.Items.Count; i++)
            {
                KeyNamePair pp = (KeyNamePair)cmbPaySelect.Items[i];
                if (pp.GetKey() == C_PaySelection_ID)
                {
                    cmbPaySelect.SelectedIndex = i;
                    return;
                }
            }
        }

        /// <summary>
        /// PaySelect changed - load Bank
        /// </summary>
        private void LoadPaySelectInfo()
        {
            log.Info("VPayPrint.loadPaySelectInfo");
            if (cmbPaySelect.SelectedIndex == -1)
            {
                return;
            }

            //  load Banks from PaySelectLine
            int C_PaySelection_ID = ((KeyNamePair)cmbPaySelect.SelectedItem).GetKey();
            m_C_BankAccount_ID = -1;
            String sql = "SELECT ps.C_BankAccount_ID, b.Name || ' ' || ba.AccountNo,"	//	1..2
                + " c.ISO_Code, CurrentBalance "										//	3..4
                + "FROM C_PaySelection ps"
                + " INNER JOIN C_BankAccount ba ON (ps.C_BankAccount_ID=ba.C_BankAccount_ID)"
                + " INNER JOIN C_Bank b ON (ba.C_Bank_ID=b.C_Bank_ID)"
                + " INNER JOIN C_Currency c ON (ba.C_Currency_ID=c.C_Currency_ID) "
                + "WHERE ps.C_PaySelection_ID=" + C_PaySelection_ID + " AND ps.Processed='Y' AND ba.IsActive='Y'";
            IDataReader idr = null;
            try
            {
                System.Threading.ThreadPool.QueueUserWorkItem(delegate
                {
                    idr = DB.ExecuteReader(sql, null, null);

                    Dispatcher.BeginInvoke(delegate
                    {
                        if (idr.Read())
                        {
                            m_C_BankAccount_ID = Util.GetValueOfInt(idr[0]);
                            lblBankName.Content = Util.GetValueOfString(idr[1]);
                            lblCurrencyName.Content = Util.GetValueOfString(idr[2]);
                            txtBalance.Text = Util.GetValueOfString(idr[3]);
                            lblNoPaymentsCount.Content = "0";
                            txtDocumentNo.Text = "";
                            //  btnEFT.IsEnabled = false;
                        }
                        else
                        {
                            m_C_BankAccount_ID = -1;
                            lblBankName.Content = ("");
                            lblCurrencyName.Content = ("");
                            txtBalance.TextAlignment = Envs.ZERO;
                            lblNoPaymentsCount.Content = "0";
                            txtDocumentNo.Text = "";
                            //   btnEFT.IsEnabled = false;
                            log.Log(Level.SEVERE, "No active BankAccount for C_PaySelection_ID=" + C_PaySelection_ID);
                        }
                        idr.Close();
                        LoadPaymentRule();
                    });

                });


            }
            catch (Exception e)
            {
                if (idr != null)
                {
                    idr.Close();
                    idr = null;
                }
                log.Log(Level.SEVERE, sql, e);
            }
        }

        /// <summary>
        /// Bank changed - load PaymentRule
        /// </summary>
        private void LoadPaymentRule()
        {
            log.Info("");
            if (m_C_BankAccount_ID == -1)
            {
                return;
            }

            // load PaymentRule for Bank
            int C_PaySelection_ID = ((KeyNamePair)cmbPaySelect.SelectedItem).GetKey();
            cmbPaymentRule.Items.Clear();
            int AD_Reference_ID = 195;
            VAdvantage.Login.Language language = VAdvantage.Login.Language.GetLanguage(Envs.GetAD_Language(Envs.GetCtx()));

            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                MLookupInfo info = MLookupFactory.GetLookUp_List(language, AD_Reference_ID);
                String infoQuery = info.query;//getquery()
                String sql = infoQuery.Substring(0, infoQuery.IndexOf(" ORDER BY"))
                    + " AND " + info.keyColumn
                    + " IN (SELECT PaymentRule FROM C_PaySelectionCheck WHERE C_PaySelection_ID=" + C_PaySelection_ID + ") "
                    + infoQuery.Substring(infoQuery.IndexOf(" ORDER BY"));

                IDataReader idr = null;

                try
                {
                    idr = DB.ExecuteReader(sql, null, null);

                    Dispatcher.BeginInvoke(delegate
                    {
                        while (idr.Read())
                        {
                            ValueNamePair pp = new ValueNamePair(Util.GetValueOfString(idr[1]), Util.GetValueOfString(idr[2]));
                            cmbPaymentRule.Items.Add(pp);
                        }
                        idr.Close();
                        if (cmbPaymentRule.Items.Count == 0)
                        {
                            log.Config("PaySel=" + C_PaySelection_ID + ", BAcct=" + m_C_BankAccount_ID + " - " + sql);
                        }
                        else
                        {
                            cmbPaymentRule.SelectedIndex = 0;
                        }
                        LoadPaymentRuleInfo();
                    });
                }
                catch (Exception e)
                {
                    if (idr != null)
                    {
                        idr.Close();
                        idr = null;
                    }
                    log.Log(Level.SEVERE, sql, e);
                }

            });
        }

        /// <summary>
        /// PaymentRule changed - load DocumentNo, NoPayments,
        ///  enable/disable EFT, Print
        /// </summary>
        private void LoadPaymentRuleInfo()
        {
            ValueNamePair pp = (ValueNamePair)cmbPaymentRule.SelectedItem;
            if (pp == null)
            {
                return;
            }
            String PaymentRule = pp.GetValue();

            log.Info("PaymentRule=" + PaymentRule);
            lblNoPaymentsCount.Content = (" ");

            int C_PaySelection_ID = ((KeyNamePair)cmbPaySelect.SelectedItem).GetKey();
            String sql = "SELECT COUNT(*) "
                + "FROM C_PaySelectionCheck "
                + "WHERE C_PaySelection_ID=" + C_PaySelection_ID;

            //  DocumentNo
            String sql1 = "SELECT CurrentNext "
                + "FROM C_BankAccountDoc "
                + "WHERE C_BankAccount_ID=" + m_C_BankAccount_ID + " AND PaymentRule  = '" + PaymentRule + "' AND IsActive='Y'";

            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                int count = DB.GetSQLValue(null, sql);

                int next = DB.GetSQLValue(null, sql1);

                Dispatcher.BeginInvoke(delegate
                {

                    lblNoPaymentsCount.Content = Util.GetValueOfString(count);
                    // btnEFT.IsEnabled = PaymentRule.Equals("T");

                    if (next != 0)
                    {
                        txtDocumentNo.Text = next.ToString();
                    }
                    else
                    {
                        log.Log(Level.SEVERE, "VPayPrint.loadPaymentRuleInfo - No active BankAccountDoc for C_BankAccount_ID="
                            + m_C_BankAccount_ID + " AND PaymentRule=" + PaymentRule);

                        ShowMessage.Error("VPayPrintNoDoc", null);
                    }
                });
            });


        }

        /// <summary>
        /// Create EFT payment
        /// </summary>
        private void Cmd_EFT()
        {
            bool res = false;
            String PaymentRule = ((ValueNamePair)cmbPaymentRule.SelectedItem).GetValue();
            log.Info(PaymentRule);

            if (cmbPaySelect.SelectedIndex == -1 || m_C_BankAccount_ID == -1
             || cmbPaymentRule.SelectedIndex == -1 || txtDocumentNo.Text == null)
            {
                ShowMessage.Error("VPayPrintNoRecords", null, "(" + Msg.Translate(Envs.GetCtx(), "C_PaySelectionLine_ID") + "=0)");
                res = false;
            }

            int C_PaySelection_ID = ((KeyNamePair)cmbPaySelect.SelectedItem).GetKey();
            int startDocumentNo = Util.GetValueOfInt(txtDocumentNo.Text);
            log.Config("C_PaySelection_ID=" + C_PaySelection_ID + ", PaymentRule=" + PaymentRule + ", DocumentNo=" + startDocumentNo);

            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                m_checks = VAdvantage.Model.MPaySelectionCheck.Get(C_PaySelection_ID, PaymentRule, startDocumentNo, null);

                //
                if (m_checks == null || m_checks.Length == 0)
                {
                    ShowMessage.Error("VPayPrintNoRecords", null, "(" + Msg.Translate(Envs.GetCtx(), "C_PaySelectionLine_ID") + " #0");
                    res = false;
                    //return false;
                }
                else
                {
                    res = true;
                }
                m_batch = VAdvantage.Model.MPaymentBatch.GetForPaySelection(Envs.GetCtx(), C_PaySelection_ID, null);
                //return true;

                if (!res)
                {
                    return;
                }
            });
            Dispose();
        }

        /// <summary>
        /// Print Checks and/or Remittance
        /// </summary>
        private void Cmd_Print()
        {
            VAdvantage.ProcessEngine.ProcessCtl pctrl = null;
            //bgw.RunWorkerAsync();
            bool res = false;
            String PaymentRule = ((ValueNamePair)cmbPaymentRule.SelectedItem).GetValue();
            log.Info(PaymentRule);

            if (cmbPaySelect.SelectedIndex == -1 || m_C_BankAccount_ID == -1
             || cmbPaymentRule.SelectedIndex == -1 || txtDocumentNo.Text == null)
            {
                ShowMessage.Error("VPayPrintNoRecords", null, "(" + Msg.Translate(Envs.GetCtx(), "C_PaySelectionLine_ID") + "=0)");
                res = false;
            }

            int C_PaySelection_ID = ((KeyNamePair)cmbPaySelect.SelectedItem).GetKey();
            int startDocumentNo = Util.GetValueOfInt(txtDocumentNo.Text);
            log.Config("C_PaySelection_ID=" + C_PaySelection_ID + ", PaymentRule=" + PaymentRule + ", DocumentNo=" + startDocumentNo);

            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                m_checks = VAdvantage.Model.MPaySelectionCheck.Get(C_PaySelection_ID, PaymentRule, startDocumentNo, null);

                if (m_checks == null || m_checks.Length == 0)
                {
                    ShowMessage.Error("VPayPrintNoRecords", null, "(" + Msg.Translate(Envs.GetCtx(), "C_PaySelectionLine_ID") + " #0");
                    res = false;
                    //return false;
                }
                else
                {
                    res = true;
                }
                m_batch = VAdvantage.Model.MPaymentBatch.GetForPaySelection(Envs.GetCtx(), C_PaySelection_ID, null);
                //return true;
                if (!res)
                {
                    return;
                }

                bool somethingPrinted = false;
                bool directPrint = !Ini.IsPropertyBool(Ini.P_PRINTPREVIEW);
                Dictionary<VAdvantage.Model.MPaySelectionCheck, String> oldCheckValues = new Dictionary<VAdvantage.Model.MPaySelectionCheck, string>();
                int checkID = 0;
                int c_payment_ID = 0;
                List<int> check_ID = new List<int>();
                foreach (VAdvantage.Model.MPaySelectionCheck check in m_checks)
                {
                    //	ReportCtrl will check BankAccountDoc for PrintFormat
                    oldCheckValues.Add(check, Util.GetValueOfString(check.Get_ValueOld("CheckNo")));
                    check.Save();
                    checkID = Util.GetValueOfInt(check.Get_ID());
                    check_ID.Add(checkID);
                    if (!somethingPrinted)
                    {
                        somethingPrinted = true;
                    }
                }

                int table_ID = 0;
                int AD_Process_ID = 0;
                string sql = "";
                int paymentTable_ID = 0;
                int paymentAD_Process_ID = 0;
                try
                {

                    sql = "select ad_table_id from ad_table where tablename = 'C_PaySelectionCheck'";
                    table_ID = Util.GetValueOfInt(DB.ExecuteScalar(sql, null, null));

                    //sql = "select ad_process_id from ad_process where value = 'CheckPrint'";
                    sql = "select ad_process_id from ad_process where ad_printformat_id = (select check_printformat_id from c_bankaccountdoc where c_bankaccount_id = (select c_bankaccount_id from c_payment where c_payment_id = (select c_payment_id from c_payselectioncheck where c_payselectioncheck_id = " + checkID + ")) and c_bankaccountdoc.isactive = 'Y' and rownum =1)";
                    AD_Process_ID = Util.GetValueOfInt(DB.ExecuteScalar(sql, null, null));

                    sql = "select ad_table_id from ad_table where tablename = 'C_Payment'";
                    paymentTable_ID = Util.GetValueOfInt(DB.ExecuteScalar(sql, null, null));

                    sql = "select ad_process_id from ad_process where value = 'PaymentPrintFormat'";
                    paymentAD_Process_ID = Util.GetValueOfInt(DB.ExecuteScalar(sql, null, null));
                    // int paymentAD_Process_ID = 313;
                }
                catch
                {

                }

                for (int j = 0; j < check_ID.Count; j++)
                {

                    int record_ID = Util.GetValueOfInt(checkID);
                    VAdvantage.ProcessEngine.ProcessInfo pi = new VAdvantage.ProcessEngine.ProcessInfo(null, AD_Process_ID, table_ID, Util.GetValueOfInt(check_ID[j]));
                    pi.SetAD_User_ID(Envs.GetCtx().GetAD_User_ID());
                    pi.SetAD_Client_ID(Envs.GetCtx().GetAD_Client_ID());

                    pctrl = new VAdvantage.ProcessEngine.ProcessCtl(null, pi, null);
                    //pctrl = new ProcessCtl(null, pi
                    pctrl.Process(m_WindowNo);

                }


                Dispatcher.BeginInvoke(delegate
                {
                    //ShowMessage.AskMessage("VPayPrintSuccess?", true, "", "").Closed += (sc, ec) =>
                    ShowMessage.AskMessage("ContinueCheckPrint?", true, "", "").Closed += (sc, ec) =>
                    {
                        if (somethingPrinted && false.Equals(((Message)sc).DialogResult))
                        {
                            Dispose();
                            return;
                        }
                        System.Threading.ThreadPool.QueueUserWorkItem(delegate
                        {
                            // int lastDocumentNo = MPaySelectionCheck.ConfirmPrint(m_checks, m_batch);
                            int lastDocumentNo = VAdvantage.Model.MPaySelectionCheck.ConfirmPrint(m_checks, m_batch);
                            if (lastDocumentNo != 0)
                            {
                                StringBuilder sb = new StringBuilder();
                                sb.Append("UPDATE C_BankAccountDoc SET CurrentNext= " + (++lastDocumentNo))
                                    .Append(" WHERE C_BankAccount_ID= " + m_C_BankAccount_ID)
                                    .Append(" AND PaymentRule=  '" + PaymentRule + "'");

                                int result = DB.ExecuteQuery(sb.ToString());
                            }

                            List<int> payment_ID = new List<int>();
                            for (int k = 0; k < check_ID.Count; k++)
                            {
                                sql = "select c_payment_id from c_PaySelectionCheck where c_PaySelectionCheck_id = " + Util.GetValueOfInt(check_ID[k]);
                                c_payment_ID = Util.GetValueOfInt(DB.ExecuteScalar(sql, null, null));
                                payment_ID.Add(c_payment_ID);
                            }

                            Dispatcher.BeginInvoke(delegate
                            {
                                ShowMessage.AskMessage("VPayPrintPrintRemittance", true, "", "").Closed += (sc1, ec1) =>
                                {
                                    if (false.Equals(((Message)sc1).DialogResult))
                                    {
                                        Dispose();
                                        return;
                                    }
                                    else
                                    {
                                        System.Threading.ThreadPool.QueueUserWorkItem(delegate
                                        {
                                            for (int l = 0; l < payment_ID.Count; l++)
                                            {
                                                //BackgroundWorker bgw1 = new BackgroundWorker();
                                                //bgw1.DoWork += (ov1, ev1) =>
                                                //{
                                                VAdvantage.ProcessEngine.ProcessInfo pin = new VAdvantage.ProcessEngine.ProcessInfo(null, paymentAD_Process_ID, paymentTable_ID, Util.GetValueOfInt(payment_ID[l]));
                                                pin.SetAD_User_ID(Envs.GetCtx().GetAD_User_ID());
                                                pin.SetAD_Client_ID(Envs.GetCtx().GetAD_Client_ID());
                                                pctrl = new VAdvantage.ProcessEngine.ProcessCtl(null, pin, null);
                                                pctrl.Process(m_WindowNo);
                                                //};

                                                //bgw1.RunWorkerAsync();
                                            }
                                            Dispatcher.BeginInvoke(delegate
                                            {
                                                SetBusy(false);
                                                Dispose();
                                            });
                                        });
                                    }
                                };
                            });
                        });
                    };
                });
            });
        }


        /// <summary>
        /// Get Checks
        /// </summary>
        /// <param name="PaymentRule">Payment Rule</param>
        /// <returns> true if payments were created</returns>
        private bool GetChecks(String PaymentRule)
        {
            //  do we have values
            if (cmbPaySelect.SelectedIndex == -1 || m_C_BankAccount_ID == -1
                || cmbPaymentRule.SelectedIndex == -1 || txtDocumentNo.Text == null)
            {
                ShowMessage.Error("VPayPrintNoRecords", null, "(" + Msg.Translate(Envs.GetCtx(), "C_PaySelectionLine_ID") + "=0)");
                return false;
            }

            //  get data
            int C_PaySelection_ID = ((KeyNamePair)cmbPaySelect.SelectedItem).GetKey();
            int startDocumentNo = Util.GetValueOfInt(txtDocumentNo.Text);
            log.Config("C_PaySelection_ID=" + C_PaySelection_ID + ", PaymentRule=" + PaymentRule + ", DocumentNo=" + startDocumentNo);
            //
            //this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

            //	get Selections
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                bool result = false;
                m_checks = VAdvantage.Model.MPaySelectionCheck.Get(C_PaySelection_ID, PaymentRule, startDocumentNo, null);

                //this.setCursor(Cursor.getDefaultCursor());
                //
                if (m_checks == null || m_checks.Length == 0)
                {
                    ShowMessage.Error("VPayPrintNoRecords", null, "(" + Msg.Translate(Envs.GetCtx(), "C_PaySelectionLine_ID") + " #0");
                    result = false;
                    //return false;
                }
                else
                {
                    result = true;
                }
                m_batch = VAdvantage.Model.MPaymentBatch.GetForPaySelection(Envs.GetCtx(), C_PaySelection_ID, null);
                //return true;

            });
            return true;
        }

        /// <summary>
        /// Export payments to file
        /// </summary>
        private void Cmd_Export()
        {
            //bool res = false;
            //String PaymentRule = ((ValueNamePair)cmbPaymentRule.SelectedItem).GetValue();
            //log.Info(PaymentRule);

            //if (cmbPaySelect.SelectedIndex == -1 || m_C_BankAccount_ID == -1
            //   || cmbPaymentRule.SelectedIndex == -1 || txtDocumentNo.Text == null)
            //{
            //    ShowMessage.Error("VPayPrintNoRecords", null, "(" + Msg.Translate(Envs.GetCtx(), "C_PaySelectionLine_ID") + "=0)");
            //    res = false;
            //}

            //int C_PaySelection_ID = ((KeyNamePair)cmbPaySelect.SelectedItem).GetKey();
            //int startDocumentNo = Util.GetValueOfInt(txtDocumentNo.Text);
            //log.Config("C_PaySelection_ID=" + C_PaySelection_ID + ", PaymentRule=" + PaymentRule + ", DocumentNo=" + startDocumentNo);

            //System.Threading.ThreadPool.QueueUserWorkItem(delegate
            //{
            //    m_checks = MPaySelectionCheck.Get(C_PaySelection_ID, PaymentRule, startDocumentNo, null);

            //    //
            //    if (m_checks == null || m_checks.Length == 0)
            //    {
            //        ShowMessage.Error("VPayPrintNoRecords", null, "(" + Msg.Translate(Envs.GetCtx(), "C_PaySelectionLine_ID") + " #0");
            //        res = false;
            //        //return false;
            //    }
            //    m_batch = MPaymentBatch.GetForPaySelection(Envs.GetCtx(), C_PaySelection_ID, null);
            //    //return true;
            //    res = true;
            //    if (!res)
            //    {
            //        return;
            //    }
            //    //  Get File Info
            //    Dispatcher.BeginInvoke(delegate
            //    {
            //        SaveFileDialog dlg = new SaveFileDialog();
            //        dlg.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
            //        dlg.DefaultFileName = Msg.GetMsg(Envs.GetCtx(), "Export");
            //        if (dlg.ShowDialog() == false)
            //        {
            //            return;
            //        }

            //    });
            //Dictionary<MPaySelectionCheck, String> oldCheckValues = new Dictionary<MPaySelectionCheck, string>();

            ////  Create File
            //foreach (MPaySelectionCheck check in m_checks)
            //{
            //    //oldCheckValues.put(check,(String)check.get_ValueOld("DocumentNo"));
            //    oldCheckValues.Add(check, Util.GetValueOfString(check.Get_ValueOld("DocumentNo")));
            //}

            ////int no = MPaySelectionCheck.exportToFile(m_checks, fc.getSelectedFile());
            //int no = MPaySelectionCheck.ExportToFile(m_checks, dlg.SafeFileName);

            ////ShowMessage.Info("Saved",null, dlg.getSelectedFile().getAbsolutePath() + "\n"
            ////    + Msg.GetMsg(Envs.GetCtx(), "NoOfLines") + "=" + no);

            //if (ShowMessage.Ask("VPayPrintSuccess?", null, ""))
            //{
            //    //	int lastDocumentNo = 
            //    MPaySelectionCheck.ConfirmPrint(m_checks, m_batch);
            //    //	document No not updated
            //}
            //else
            //{
            //    foreach (MPaySelectionCheck check in m_checks)
            //    {
            //        check.SetCheckNo(oldCheckValues[check]);
            //        check.Save();
            //    }
            //}

            //Dispatcher.BeginInvoke(delegate
            //{
            //    Dispose();
            //});

            // });
        }

        /**
       *  Get Customer/Vendor Info.
       *  Based on BP_ static variables
       *  @param C_BPartner_ID BPartner
       *  @return info array
       */
        private static String[] GetBPartnerInfo(int C_BPartner_ID)
        {
            String[] bp = new String[10];

            String sql = "SELECT bp.Value, bp.Name, c.Name AS Contact, "
                + "a.Address1, a.Address2, a.City, r.Name AS Region, a.Postal, "
                + "cc.Name AS Country, bp.ReferenceNo "
                /*//jz use SQL standard outer join
                + "FROM C_BPartner bp, AD_User c, C_BPartner_Location l, C_Location a, C_Region r, C_Country cc "
                + "WHERE bp.C_BPartner_ID=?"        // #1
                + " AND bp.C_BPartner_ID=c.C_BPartner_ID(+)"
                + " AND bp.C_BPartner_ID=l.C_BPartner_ID"
                + " AND l.C_Location_ID=a.C_Location_ID"
                + " AND a.C_Region_ID=r.C_Region_ID(+)"
                + " AND a.C_Country_ID=cc.C_Country_ID "
                */
                + "FROM C_BPartner bp "
                + "LEFT OUTER JOIN AD_User c ON (bp.C_BPartner_ID=c.C_BPartner_ID) "
                + "INNER JOIN C_BPartner_Location l ON (bp.C_BPartner_ID=l.C_BPartner_ID) "
                + "INNER JOIN C_Location a ON (l.C_Location_ID=a.C_Location_ID) "
                + "LEFT OUTER JOIN C_Region r ON (a.C_Region_ID=r.C_Region_ID) "
                + "INNER JOIN C_Country cc ON (a.C_Country_ID=cc.C_Country_ID) "
                + "WHERE bp.C_BPartner_ID= " + C_BPartner_ID          // #1
                + " ORDER BY l.IsBillTo DESC";

            IDataReader idr = null;
            try
            {
                //
                idr = DB.ExecuteReader(sql, null, null);

                if (idr.Read())
                {
                    bp[BP_VALUE] = idr.GetString(0);
                    if (bp[BP_VALUE] == null)
                        bp[BP_VALUE] = "";
                    bp[BP_NAME] = idr.GetString(1);
                    if (bp[BP_NAME] == null)
                        bp[BP_NAME] = "";
                    bp[BP_CONTACT] = idr.GetString(2);
                    if (bp[BP_CONTACT] == null)
                        bp[BP_CONTACT] = "";
                    bp[BP_ADDR1] = idr.GetString(3);
                    if (bp[BP_ADDR1] == null)
                        bp[BP_ADDR1] = "";
                    bp[BP_ADDR2] = idr.GetString(4);
                    if (bp[BP_ADDR2] == null)
                        bp[BP_ADDR2] = "";
                    bp[BP_CITY] = idr.GetString(5);
                    if (bp[BP_CITY] == null)
                        bp[BP_CITY] = "";
                    bp[BP_REGION] = idr.GetString(6);
                    if (bp[BP_REGION] == null)
                        bp[BP_REGION] = "";
                    bp[BP_POSTAL] = idr.GetString(7);
                    if (bp[BP_POSTAL] == null)
                        bp[BP_POSTAL] = "";
                    bp[BP_COUNTRY] = idr.GetString(8);
                    if (bp[BP_COUNTRY] == null)
                        bp[BP_COUNTRY] = "";
                    bp[BP_REFNO] = idr.GetString(9);
                    if (bp[BP_REFNO] == null)
                        bp[BP_REFNO] = "";
                }
                idr.Close();
            }
            catch (Exception e)
            {
                if (idr != null)
                {
                    idr.Close();
                }
                log.Log(Level.SEVERE, sql, e);
            }

            return bp;
        }

        /**
         *  Get Bank Account Info for tarGet Accpimt.
         *  Based on BP_ static variables
         *  @param C_BPartner_ID BPartner
         *  @return info array
         */
        private static String[] GetBPBankAccountInfo(int C_BP_BankAccount_ID)
        {
            String[] bp = new String[10];

            String sql = "SELECT bpba.RoutingNo, bpba.AccountNo, bpba.A_Name, bpba.A_City, bpba.BBAN, "
                + "bpba.IBAN, ba.Name, ba.RoutingNo, ba.SwiftCode "
                /*//jz use SQL standard outer join
                + "FROM C_BPartner bp, AD_User c, C_BPartner_Location l, C_Location a, C_Region r, C_Country cc "
                + "WHERE bp.C_BPartner_ID=?"        // #1
                + " AND bp.C_BPartner_ID=c.C_BPartner_ID(+)"
                + " AND bp.C_BPartner_ID=l.C_BPartner_ID"
                + " AND l.C_Location_ID=a.C_Location_ID"
                + " AND a.C_Region_ID=r.C_Region_ID(+)"
                + " AND a.C_Country_ID=cc.C_Country_ID "
                */
                + "FROM C_BP_BankAccount bpba "
                + "LEFT OUTER JOIN C_Bank ba ON (bpba.C_Bank_ID = ba.C_Bank_ID) "
                + "WHERE bpba.C_BP_BankAccount_ID=" + C_BP_BankAccount_ID;        // #1

            IDataReader idr = null;
            try
            {
                idr = DB.ExecuteReader(sql, null, null);
                if (idr.Read())
                {
                    bp[BPBA_RoutingNo] = idr.GetString(1);
                    if (bp[BPBA_RoutingNo] == null)
                        bp[BPBA_RoutingNo] = "";
                    bp[BPBA_AccountNo] = idr.GetString(2);
                    if (bp[BPBA_AccountNo] == null)
                        bp[BPBA_AccountNo] = "";
                    bp[BPBA_AName] = idr.GetString(3);
                    if (bp[BPBA_AName] == null)
                        bp[BPBA_AName] = "";
                    bp[BPBA_ACity] = idr.GetString(4);
                    if (bp[BPBA_ACity] == null)
                        bp[BPBA_ACity] = "";
                    bp[BPBA_BBAN] = idr.GetString(5);
                    if (bp[BPBA_BBAN] == null)
                        bp[BPBA_BBAN] = "";
                    bp[BPBA_IBAN] = idr.GetString(6);
                    if (bp[BPBA_IBAN] == null)
                        bp[BPBA_IBAN] = "";
                    bp[BA_Name] = idr.GetString(7);
                    if (bp[BA_Name] == null)
                        bp[BA_Name] = "";
                    bp[BA_RoutingNo] = idr.GetString(8);
                    if (bp[BA_RoutingNo] == null)
                        bp[BA_RoutingNo] = "";
                    bp[BA_SwitftCode] = idr.GetString(9);
                    if (bp[BA_SwitftCode] == null)
                        bp[BA_SwitftCode] = "";
                }
                idr.Close();
            }
            catch (Exception e)
            {
                if (idr != null)
                {
                    idr.Close();
                }
                log.Log(Level.SEVERE, sql, e);
            }

            return bp;
        }

        private void SetBusy(bool value)
        {
            this.IsEnabled = !value;
            busyWindow.Visibility = value ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            // txtBusy.Visibility = value ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
        }

        private void busyWindow_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;
        }

        private void txtBalance_TextChanged(object sender, TextChangedEventArgs e)
        {

        }
    }
}
